// 引入express框架
var express = require('express');
// 创建路由对象
var router = express.Router();
// 引入用户、角色、菜单数据模型
let userModel = require('../db/user');
let roleModel = require('../db/role');
let menuModel = require('../db/menu');

/* GET home page. */
// 首页路由，渲染index页面
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

// 登录
router.post('/login', async function(req, res, next) {
  const { name, password } = req.body;

  try {
    // 1. 根据用户名查找用户
    const user = await userModel.findOne({ name });

    if (!user) {
      return res.json({
        code: 400,
        msg: '用户名不存在'
      });
    }

    // 2. 验证密码
    if (user.password !== password) {
      return res.json({
        code: 400,
        msg: '密码错误'
      });
    }

    // 3. 登录成功，返回用户信息
    res.json({
      code: 200,
      msg: '登录成功',
      data: {
        _id: user._id,
        name: user.name,
        roles: user.roles
      }
    });

  } catch (err) {
    console.error(err);
    res.json({
      code: 500,
      msg: '服务器内部错误'
    });
  }
});



// 获取所有用户信息
router.get('/getUsers',async function(req,res,next){
  let users = await userModel.find({});
  // console.log('获取到的用户数据:', users);
  res.json({
    code:200,
    data:users
  });
})

// 获取所有角色信息
router.get('/getRoles',async function(req,res,next){
  let roles = await roleModel.find({});
  res.json({
    code:200,
    data:roles
  });
})

// 获取所有菜单信息
router.get('/getMenus',async function(req,res,next){
  let menus = await menuModel.find({});
  res.json({
    code:200,
    data:menus
  });
})

// 保存用户的角色权限
router.post("/saveRoles",async function(req,res,next){
  let {_id,roles} = req.body;
  try{
    let result = await userModel.findByIdAndUpdate(_id,{roles:roles});
    res.json({
      code:200,
      msg:"更新成功",
      data:result
    })
  }catch(err){
    console.error(err);
    res.json({
      code:500,
      msg:"更新失败"
    })
  }
})

// 保存角色的菜单权限
router.post("/updateRoleMenus",async function(req,res,next){
  let {_id,menus} = req.body;
  console.log(menus);
  try{
    let result = await roleModel.findByIdAndUpdate(_id,{menus:menus});
    console.log(result);
    res.json({
      code:200,
      msg:"更新成功",
      data:result
    })
  }catch(err){
    console.error(err);
    res.json({
      code:500,
      msg:"更新失败"
    })
  }
})

// 构建树状菜单的递归函数
function constructTree(menus,children,path){
  menus.map(m=>{
    if(m.pid === path){
      console.log(m.title);
      
      let childrenItem = {
        key:m.path,
        title:m.title,
        children:[],
        label:m.title,
        order:m.order
      }
      children.push(childrenItem)
      constructTree(menus,childrenItem.children,m.path)
    }
  })
}

// 获取所有树状菜单数据接口
router.get('/getMenuTree',async function(req,res,next){ 
  let menus = await menuModel.find({});
  console.log(menus[0]);
  
  let treeDate = []
  menus.map(m=>{
    // 最顶层的菜单
    if(m.pid === '/'){
      let treeItem = {
        key:m.path,
        title:m.title,
        children:[],
        label:m.title
      }
      treeDate.push(treeItem)
      constructTree(menus,treeItem.children,m.path)
    }
  })
  // console.log(treeDate);
  
  res.json({
    code:200,
    data:treeDate
  })


})
// 获取对应用户树状菜单数据接口
router.get('/getUserTree',async function(req,res,next){

  const { userId } = req.query;
  
  const user = await userModel.findById(userId);
  if (!user) return res.json({ code: 404, msg: '用户不存在' });

  // 1. 获取用户所有角色对应的菜单
  const userRoles = user.roles.split(',');
  const roles = await roleModel.find({ id: { $in: userRoles } });
  
  
  // 2. 获取所有菜单路径（去重）
  const menuPaths = [...new Set(
    roles.flatMap(role => role.menus ? role.menus.split(',') : [])
  )];
  // console.log(menuPaths);
  

  // 3. 查询有权限的菜单并构建树
  const menus = await menuModel.find({ path: { $in: menuPaths } });
  // let menus = await menuModel.find({});

  


  let treeDate = []
  menus.map(m=>{
    // 最顶层的菜单
    if(m.pid === '/'){
      let treeItem = {
        key:m.path,
        title:m.title,
        children:[],
        label:m.title,
        order:m.order
      }
      treeDate.push(treeItem)
      constructTree(menus,treeItem.children,m.path)
    }
  })
  console.log(treeDate);
  
  res.json({
    code:200,
    data:treeDate
  })
})

// 新增角色接口
router.post('/addRole', async function(req, res, next) {
  const { title, menus } = req.body;
  try {
    const newRole = await roleModel.create({ title, menus });
    res.json({ code: 200, msg: '添加角色成功', data: newRole });
  } catch (err) {
    console.error(err);
    res.json({ code: 500, msg: '添加角色失败' });
  }
});

// 删除角色接口
router.post('/deleteRole', async function(req, res, next) {
  const { _id } = req.body;
  try {
    await roleModel.findByIdAndDelete(_id);
    res.json({ code: 200, msg: '删除角色成功' });
  } catch (err) {
    console.error(err);
    res.json({ code: 500, msg: '删除角色失败' });
  }
});

// 更新菜单 path 和 pid
router.post('/updateMenu', async function(req, res, next) {
  const { _id, path, pid } = req.body;
  try {
    const result = await menuModel.findByIdAndUpdate(_id, { path, pid });
    res.json({ code: 200, msg: '菜单更新成功', data: result });
  } catch (err) {
    console.error(err);
    res.json({ code: 500, msg: '菜单更新失败' });
  }
});

// 导出路由对象
module.exports = router;
